<script>
import QuarterlyAccountSearchForm from '@/mixins/quarterly-account-search-form'
import QuarterlyAccountDetails from '@/mixins/quarterly-account-details'
import QuarterlyAccountTableLists from '@/mixins/quarterly-account-table-lists'

import {
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE, ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID, PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
  TABLE_UNDER_REPORT,
} from '@/config'
import quickExport from './quick-export'
import { uploadEnergyReport } from '@/api/energyReport'
import { uuid } from '@/utils'

export default {
  name: 'energy-utilization-status-report-enterprise',
  mixins: [
    QuarterlyAccountSearchForm,
    QuarterlyAccountTableLists,
    QuarterlyAccountDetails,
  ],
  created () {
    // 年度
    this.quarter = '5'
  },
  data () {
    return {
      columns: [
        {
          lable: '表名',
          prop: 'alias',
          width: 120
        },
        {
          label: '表全称',
          prop: 'name'
        },
      ],
    }
  },
  methods: {
    /**
     * @override 查询年报报表数据列表
     * @returns {Promise<unknown>}
     */
    queryLists () {
      this.loading = true
      // 年度
      return new Promise(() => {
        setTimeout(() => {
          this.lists = [
            ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
            ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
            ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
            TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID,
            PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID,
            ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID,
          ].map((v, i) => ({
            id: uuid(),
            alias: [
              '年报表1-1',
              '年报表1-2',
              '年报表1-2-1',
              '年报表1-3',
              '年报表1-4',
              '年报表1-5',
            ][i],
            tableAccountId: v,
            name: this.getTableName(v)
          }))
          this.loading = false
        }, 200)
      })
    },

    // 一键生成年报报表
    quickExport () {
      const fileName = `${this.year}年${this.enterpriseName}年度报表`
      quickExport(this.year, this.quarter, fileName)
    },
    // 上传报表
    uploadEnergyReport (file, year) {
      return uploadEnergyReport(file, year).then(res => {
        this.$message.success('上传成功')
      })
    },
    fileChangeHandler (evt) {
      const target = evt.target
      const file = target.files[0]
      const year = this.year || new Date().getFullYear()
      if (file) {
        this.uploadEnergyReport(file, year).finally(() => {
          // 清空input
          target.value = ''
        })
      }
    },
    saveUnderReport () {
      // 校验不通过
       if (this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.hasError) {
        this.$message.warning('报表数据校验不通过，请检查')
        return;
      }

      if (this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.validateInformant) {
        if (!this.$refs.quarterlyAccountTable.validateInformant()) {
          // this.$message.warning('填报人信息校验不通过，请检查')
          return;
        }
      }

      this.saveOrUpdate(TABLE_UNDER_REPORT)
    },
    check () {}
  },
}
</script>

<template>
  <div class="padding flex direction-column width-100 height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item label="年份">
          <el-date-picker type="year" :clearable="false" v-model="year" value="yyyy" value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="primary" icon="el-icon-bottom" @click="quickExport">生成年报</el-button>
          <el-button type="primary" icon="el-icon-top" class="position-relative">
            上传年报
            <input type="file" class="opacity-0 absolute inset-0 file-input" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="fileChangeHandler">
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="flex-1 overflow-auto dark-table-wrapper">
      <el-table
        v-loading="loading"  :data="lists"
        height="100%"
        :header-cell-style="{
          color: 'white',
          backgroundColor: themeColor,
        }"
      >
        <div slot="empty" class="empty-lists">
          <i class="i-custom:search"></i>
          <span class="empty-text">暂无数据</span>
        </div>
        <el-table-column v-for="column in columns" :key="column.prop" v-bind="column"></el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="{ row }">
            <td-button title="编辑" @click="edit(row)">
              <i class="i-custom:editor"></i>
            </td-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="showTableAccount" class="padding table-account-details">
      <component
        :is="tableComponent"
        ref="quarterlyAccountTable"
        :year="year" :quarter="quarter"
        :columns="tableColumns" :name="tableName" :t-id="tableAccountId"
        :enterprise-id="enterpriseId" :enterprise-name="enterpriseName"
        :readonly="readonly"
      >
        <template #title="{ title, seriesNo }">
          <div class="flex align-center position-relative">
            <el-button type="primary" icon="el-icon-back" circle @click="back(!showButton)"></el-button>
            <span v-if="autoSaveAble" class="last-save-timestamp">最近保存 {{ lastSaveTimestamp }}</span>
            <h2 class="margin-horizontal-auto" style="font-weight: normal;">
              {{title}}
              <small v-if="seriesNo">（{{seriesNo}}）</small>
            </h2>
            <template v-if="showButton">
              <el-button type="success" @click="loadPrevData">加载上期数据</el-button>
              <el-button type="primary" @click="saveStage">保存为草稿</el-button>
              <el-button type="warning" @click="saveUnderReport">保存</el-button>
            </template>
          </div>
        </template>
      </component>
    </div>
  </div>
</template>
